#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <sstream>
using namespace std; 
int main()
{
    //创建套接字
    int listen_sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(listen_sock < 0)
    {
        perror("socket");
        return 0;
    }
    //绑定地址
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(28989);
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    int ret = bind(listen_sock,(struct sockaddr*)&addr,sizeof(addr));
    if(ret < 0)
    {
        perror("bind");
        return 0;
    }
    //监听
    ret = listen(listen_sock,1);
    if(ret < 0)
    {
        perror("listen");
        return 0;
    }

    //接收新连接
    struct sockaddr_in cli_addr;
    socklen_t cli_addrlen = sizeof(cli_addr);
    int newsockfd =  accept(listen_sock,(struct sockaddr*)&addr,&cli_addrlen);
    if(newsockfd < 0)
    {
        perror("accept");
        return 0;
    }
    printf("accept newsockfd from %s:%d\n",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port));

    while(1)
    {
        //接收
        char buf[1024]={0};
        ssize_t recv_size =  recv(newsockfd,buf,sizeof(buf)-1,0);
        if(recv_size < 0)
        {
            perror("recv");
            continue;
        }
        else if(recv_size == 0)
        {
            printf("peer close connet\n");
            close(newsockfd);
            break;
        }
        printf("%s\n",buf);

        //发送
        string body = "<html><h1>welcome home</h1></html>";
        stringstream ss;
        ss << "HTTP/1.1 302 Found\r\n";//请求首行
        //ss << "Content-Type:text/html\r\n";//请求体
        //ss << "Content-Length:"<< body.size()<<"\r\n";//请求体
        ss << "Location:https://www.baidu.com/\r\n";//跳转到百度页面
        ss << "\r\n";//空行

        send(newsockfd,ss.str().c_str(),ss.str().size(),0);
        send(newsockfd,body.c_str(),body.size(),0);
    }
    close(listen_sock);
    return 0;
}
